package com.wangjiang.mario.admin.web.admin.controller.v1;

import com.wangjiang.mario.admin.common.annotation.LogTrack;
import com.wangjiang.mario.admin.core.shiro.token.JwtToken;
import com.wangjiang.mario.admin.common.rest.ResultGenerator;
import com.wangjiang.mario.admin.common.rest.entity.Result;
import com.wangjiang.mario.admin.core.shiro.utils.ShiroUtils;
import com.wangjiang.mario.admin.system.domain.service.JwtService;
import com.wangjiang.mario.admin.system.domain.service.UserService;
import com.wangjiang.mario.admin.system.domain.service.WxMicroappService;
import com.wangjiang.mario.admin.system.object.token.TokenResult;
import com.wangjiang.mario.admin.system.object.user.UserLoginDto;
import com.wangjiang.mario.admin.system.object.user.UserRegisterDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("")
@Api(value = "/user", tags = "注册登录相关接口")
public class AuthController {

    private static final Logger logger = LoggerFactory.getLogger(AuthController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private JwtService jwtService;

    @Autowired
    private WxMicroappService wxMicroappService;

    /**
     * 注册
     *
     * @param user
     * @return
     */
    @PostMapping("/register")
    @ApiOperation(value = "注册")
    @LogTrack(title = "注册")
    public Result register(@RequestBody UserRegisterDto user) {
        return ResultGenerator.genSuccessResult("注册成功", userService.register(user));
    }


    /**
     * 登录接口
     *
     * @param userLoginDto
     * @return
     */
    @PostMapping("/login")
    @ApiOperation(value = "登陆")
    @LogTrack(title = "登陆")
    public Result login(@RequestBody UserLoginDto userLoginDto) {
        TokenResult result = userService.login(userLoginDto);

        Subject subject = ShiroUtils.getSubject();
        JwtToken token = new JwtToken(result.getAccess_token());
        try {
            subject.login(token);
//            UserRoleMenuVo userRoleMenuVo = userService.getUserWithRoleAndMenuByUUid(jwtService.getUUid((String) token.getCredentials()));
//            ShiroUtils.setCurrentUser(userRoleMenuVo, (String) token.getCredentials());
        } catch (AuthenticationException e) {
            logger.error(e.getMessage());
            token.clear();
            return ResultGenerator.genFailResult("登录失败，用户名或密码错误！");
        }
        return ResultGenerator.genSuccessResult("登录成功", result);
    }

    /**
     * me
     *
     * @return
     */
    @PostMapping("/me")
    @ApiOperation(value = "当前用户，通过token判断")
    @RequiresAuthentication // 需要登录
    @LogTrack(title = "获取当前用户信息")
    public Result me() {
        return ResultGenerator.genSuccessResult(userService.getMe());
    }

    /**
     * 登出接口
     * 通过头部token
     *
     * @return
     */
    @PostMapping("/logout")
    @ApiOperation(value = "登出")
    @LogTrack(title = "登出")
    public Result logout() {
        return ResultGenerator.genSuccessResult("登出成功",  userService.logout());
    }


    /**
     * 微信小程序登录
     */
    @GetMapping("wxapp/appid/{appid}/login")
    @ApiOperation(value = "微信小程序登录, 获取openid")
    @LogTrack(title = "微信小程序登录")
    public Result wxAppLogin(
            @PathVariable String appid,
            @RequestParam String code
    ) {
        return ResultGenerator.genSuccessResult("登录成功", wxMicroappService.wxAppLogin(appid, code));
    }

    /**
     * 微信小程序获取用户信息
     */
    @GetMapping("wxapp/appid/{appid}/userinfo")
    @ApiOperation(value = "微信小程序获取用户详细信息（有openid）")
    @LogTrack(title = "微信小程序获取用户详细信息")
    public Result wxAppUserinfo(
            @PathVariable String appid,
            @RequestParam String code,
            @RequestParam String encryptedData,
            @RequestParam String iv
    ) {
        return ResultGenerator.genSuccessResult("获取用户信息成功", wxMicroappService.getUserInfo(appid, code, encryptedData, iv));
    }

    /**
     * 前台其实不需要存放这个access_token
     * 微信程序获取access_token
     * appid = wx3007d6086b29908c
     */
    @GetMapping("wxapp/access_token")
    @ApiOperation(value = "微信小程序获取个人信息")
    @LogTrack(title = "微信小程序获取个人信息")
    public Result getme (
            @RequestParam String appid
    ) {
        return ResultGenerator.genSuccessResult("获取成功", wxMicroappService.getAccessToken(appid));
    }


}
